package won.user;

import won.db.DBConnect;
import won.model.Book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Scanner;

import static java.lang.System.out;

public class BookManager {
    static Scanner input = new Scanner(System.in);
    public BookManager() {

    }

        public static AbstractBook findBook(String bookname){
            ResultSet resultSet;
            PreparedStatement prestmt;
            AbstractBook book = null;
            try {
                String sql = "SELECT * FROM book WHERE bookname = ? ";
                prestmt = DBConnect.getConnect().prepareStatement(sql);
                prestmt.setString(1, bookname);
                resultSet = prestmt.executeQuery();

                if (resultSet.next()) {
                    java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
                    long id = resultSet.getLong("id");
                        book = new AcademicBook(bookname, 15, date , "in", "a"); // 假设Teacher类有对应的构造器
                }

                if (resultSet != null) {
                    resultSet.close();
                }
                if (prestmt != null) {
                    prestmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return book;
        }

    public static void addBook(AbstractBook book) {
        // 检查书籍是否已经存在，如果存在，则无法添加
        if (findBook(book.getBookName()) != null) {
            out.println("Book already exists. Failed to add the book.");
            return;
        }

        // 书籍不存在，执行添加操作
        Connection connection = DBConnect.getConnect();
        PreparedStatement prestmt = null;
        try {
            String sql = "INSERT INTO book (bookname, dailyfine, borrowdate, status, type) VALUES (?, ?, ?, ?, ?)";
            prestmt = connection.prepareStatement(sql);
            prestmt.setString(1, book.getBookName());
            prestmt.setInt(2, book.getDailyFine());
            prestmt.setDate(3, new java.sql.Date(book.getBorrowDate().getTime())); // 确保传递的是 java.sql.Date
            prestmt.setString(4, book.getStatus());
            prestmt.setString(5, book.getType());
            prestmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 确保资源被关闭，避免资源泄露
            try {
                if (prestmt != null) {
                    prestmt.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        out.println("Book added successfully!");
    }

}
